package com.laixu.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class LoggingInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录请求开始时间
        request.setAttribute("startTime", System.currentTimeMillis());

        // 记录请求身份（这里简单假设为匿名）
        String requestIdentity = "laixu" +
                "";
        // 记录请求路径
        String requestPath = request.getRequestURI();
        // 记录请求方式
        String requestMethod = request.getMethod();
        // 记录调用方法名字
        String methodName = handler.toString();

        logger.info("请求身份: {}, 请求路径: {}, 请求方式: {}, 请求时间: {}, 调用方法名字: {}",
                requestIdentity, requestPath, requestMethod, new Date(), methodName);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 可以在这里进行一些额外的处理
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 记录请求结束时间
        long endTime = System.currentTimeMillis();
        // 获取请求开始时间
        long startTime = (long) request.getAttribute("startTime");
        // 计算耗费时间
        long spendTime = endTime - startTime;

        logger.info("请求处理完成，耗费时间: {} 毫秒", spendTime);
    }
}